package com.guaoran.distributed.io.aio.one;

import javax.print.attribute.standard.Finishings;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author gucheng
 * @Description AIOServer
 * 2019-04-19 15:22
 */
public class AIOServer {
    private final int port;
    public AIOServer(int port){
        this.port = port;
        listener();
    }
    private void listener() {
        try {
            //线程缓冲池，为了体现异步
            ExecutorService executorService = Executors.newCachedThreadPool();
            //给线程池初始化一个线程
            AsynchronousChannelGroup threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService,1);
            final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(threadGroup);
            server.bind(new InetSocketAddress(port));
            System.out.println("服务已启动，监听端口："+port);

            final Map<String,Integer> count = new ConcurrentHashMap<>();
            count.put("count",0);

            //开始等待客户端连接
            //实现一个CompletionHandler 的接口，匿名的实现类
            server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
                final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
                //实现IO操作完成的方法
                @Override
                public void completed(AsynchronousSocketChannel result, Object attachment) {
                    count.put("count",count.get("count")+1);
                    System.out.println(count.get("count"));
                    try {
                        buffer.clear();
                        result.read(buffer).get();
                        buffer.flip();
                        result.write(buffer);
                        buffer.flip();
                    } catch (Exception e) {
                        System.out.println(e.toString());
                    } finally {
                        try {
                            result.close();
                            server.accept(null, this);
                        } catch (Exception e) {
                            System.out.println(e.toString());
                        }
                    }
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.err.println("failed.....");
                }
            });
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException ex) {
                System.out.println(ex);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new AIOServer(8080).listener();
    }


}
